

<!DOCTYPE html>
<html class="writer-html5" lang="zh" >
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>调试spiders &mdash; Scrapy 2.3.0 文档</title>
  

  
  <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/tooltipster.custom.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/tooltipster.bundle.min.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/tooltipster-sideTip-shadow.min.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/tooltipster-sideTip-punk.min.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/tooltipster-sideTip-noir.min.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/tooltipster-sideTip-light.min.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/tooltipster-sideTip-borderless.min.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/micromodal.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/sphinx_rtd_theme.css" type="text/css" />

  
  
  
  

  
  <!--[if lt IE 9]>
    <script src="../_static/js/html5shiv.min.js"></script>
  <![endif]-->
  
    
      <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
        <script src="../_static/jquery.js"></script>
        <script src="../_static/underscore.js"></script>
        <script src="../_static/doctools.js"></script>
        <script src="../_static/language_data.js"></script>
        <script src="../_static/js/hoverxref.js"></script>
        <script src="../_static/js/tooltipster.bundle.min.js"></script>
        <script src="../_static/js/micromodal.min.js"></script>
    
    <script type="text/javascript" src="../_static/js/theme.js"></script>

    
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="next" title="蜘蛛合约" href="contracts.html" />
    <link rel="prev" title="常见问题" href="../faq.html" /> 
</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">
    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >
          

          
            <a href="../index.html" class="icon icon-home" alt="Documentation Home"> Scrapy
          

          
          </a>

          
            
            
              <div class="version">
                2.3
              </div>
            
          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        
        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <p class="caption"><span class="caption-text">第一步</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../intro/overview.html">Scrapy一目了然</a></li>
<li class="toctree-l1"><a class="reference internal" href="../intro/install.html">安装指南</a></li>
<li class="toctree-l1"><a class="reference internal" href="../intro/tutorial.html">Scrapy 教程</a></li>
<li class="toctree-l1"><a class="reference internal" href="../intro/examples.html">实例</a></li>
</ul>
<p class="caption"><span class="caption-text">基本概念</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="commands.html">命令行工具</a></li>
<li class="toctree-l1"><a class="reference internal" href="spiders.html">蜘蛛</a></li>
<li class="toctree-l1"><a class="reference internal" href="selectors.html">选择器</a></li>
<li class="toctree-l1"><a class="reference internal" href="items.html">项目</a></li>
<li class="toctree-l1"><a class="reference internal" href="loaders.html">项目加载器</a></li>
<li class="toctree-l1"><a class="reference internal" href="shell.html">Scrapy shell</a></li>
<li class="toctree-l1"><a class="reference internal" href="item-pipeline.html">项目管道</a></li>
<li class="toctree-l1"><a class="reference internal" href="feed-exports.html">Feed 导出</a></li>
<li class="toctree-l1"><a class="reference internal" href="request-response.html">请求和响应</a></li>
<li class="toctree-l1"><a class="reference internal" href="link-extractors.html">链接提取器</a></li>
<li class="toctree-l1"><a class="reference internal" href="settings.html">设置</a></li>
<li class="toctree-l1"><a class="reference internal" href="exceptions.html">例外情况</a></li>
</ul>
<p class="caption"><span class="caption-text">内置服务</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="logging.html">登录</a></li>
<li class="toctree-l1"><a class="reference internal" href="stats.html">统计数据集合</a></li>
<li class="toctree-l1"><a class="reference internal" href="email.html">发送电子邮件</a></li>
<li class="toctree-l1"><a class="reference internal" href="telnetconsole.html">远程登录控制台</a></li>
<li class="toctree-l1"><a class="reference internal" href="webservice.html">Web服务</a></li>
</ul>
<p class="caption"><span class="caption-text">解决具体问题</span></p>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../faq.html">常见问题</a></li>
<li class="toctree-l1 current"><a class="current reference internal" href="#">调试spiders</a><ul>
<li class="toctree-l2"><a class="reference internal" href="#parse-command">解析命令</a></li>
<li class="toctree-l2"><a class="reference internal" href="#scrapy-shell">Scrapy Shell</a></li>
<li class="toctree-l2"><a class="reference internal" href="#open-in-browser">在浏览器中打开</a></li>
<li class="toctree-l2"><a class="reference internal" href="#logging">登录</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="contracts.html">蜘蛛合约</a></li>
<li class="toctree-l1"><a class="reference internal" href="practices.html">常用做法</a></li>
<li class="toctree-l1"><a class="reference internal" href="broad-crawls.html">宽爬行</a></li>
<li class="toctree-l1"><a class="reference internal" href="developer-tools.html">使用浏览器的开发人员工具进行抓取</a></li>
<li class="toctree-l1"><a class="reference internal" href="dynamic-content.html">选择动态加载的内容</a></li>
<li class="toctree-l1"><a class="reference internal" href="leaks.html">调试内存泄漏</a></li>
<li class="toctree-l1"><a class="reference internal" href="media-pipeline.html">下载和处理文件和图像</a></li>
<li class="toctree-l1"><a class="reference internal" href="deploy.html">部署蜘蛛</a></li>
<li class="toctree-l1"><a class="reference internal" href="autothrottle.html">AutoThrottle 扩展</a></li>
<li class="toctree-l1"><a class="reference internal" href="benchmarking.html">标杆管理</a></li>
<li class="toctree-l1"><a class="reference internal" href="jobs.html">作业：暂停和恢复爬行</a></li>
<li class="toctree-l1"><a class="reference internal" href="coroutines.html">协同程序</a></li>
<li class="toctree-l1"><a class="reference internal" href="asyncio.html">asyncio</a></li>
</ul>
<p class="caption"><span class="caption-text">扩展Scrapy</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="architecture.html">体系结构概述</a></li>
<li class="toctree-l1"><a class="reference internal" href="downloader-middleware.html">下载器中间件</a></li>
<li class="toctree-l1"><a class="reference internal" href="spider-middleware.html">蜘蛛中间件</a></li>
<li class="toctree-l1"><a class="reference internal" href="extensions.html">扩展</a></li>
<li class="toctree-l1"><a class="reference internal" href="api.html">核心API</a></li>
<li class="toctree-l1"><a class="reference internal" href="signals.html">信号</a></li>
<li class="toctree-l1"><a class="reference internal" href="exporters.html">条目导出器</a></li>
</ul>
<p class="caption"><span class="caption-text">其余所有</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../news.html">发行说明</a></li>
<li class="toctree-l1"><a class="reference internal" href="../contributing.html">为 Scrapy 贡献</a></li>
<li class="toctree-l1"><a class="reference internal" href="../versioning.html">版本控制和API稳定性</a></li>
</ul>

            
          
        </div>
        
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../index.html">Scrapy</a>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        
          















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../index.html" class="icon icon-home"></a> &raquo;</li>
        
      <li>调试spiders</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
            
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <div class="section" id="debugging-spiders">
<span id="topics-debug"></span><h1>调试spiders<a class="headerlink" href="#debugging-spiders" title="永久链接至标题">¶</a></h1>
<p>本文介绍了调试spider的最常用技术。请考虑下面的蜘蛛：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">scrapy</span>
<span class="kn">from</span> <span class="nn">myproject.items</span> <span class="kn">import</span> <span class="n">MyItem</span>

<span class="k">class</span> <span class="nc">MySpider</span><span class="p">(</span><span class="n">scrapy</span><span class="o">.</span><span class="n">Spider</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="s1">&#39;myspider&#39;</span>
    <span class="n">start_urls</span> <span class="o">=</span> <span class="p">(</span>
        <span class="s1">&#39;http://example.com/page1&#39;</span><span class="p">,</span>
        <span class="s1">&#39;http://example.com/page2&#39;</span><span class="p">,</span>
        <span class="p">)</span>

    <span class="k">def</span> <span class="nf">parse</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">response</span><span class="p">):</span>
        <span class="c1"># &lt;processing code not shown&gt;</span>
        <span class="c1"># collect `item_urls`</span>
        <span class="k">for</span> <span class="n">item_url</span> <span class="ow">in</span> <span class="n">item_urls</span><span class="p">:</span>
            <span class="k">yield</span> <span class="n">scrapy</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="n">item_url</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">parse_item</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">parse_item</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">response</span><span class="p">):</span>
        <span class="c1"># &lt;processing code not shown&gt;</span>
        <span class="n">item</span> <span class="o">=</span> <span class="n">MyItem</span><span class="p">()</span>
        <span class="c1"># populate `item` fields</span>
        <span class="c1"># and extract item_details_url</span>
        <span class="k">yield</span> <span class="n">scrapy</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="n">item_details_url</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">parse_details</span><span class="p">,</span> <span class="n">cb_kwargs</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;item&#39;</span><span class="p">:</span> <span class="n">item</span><span class="p">})</span>

    <span class="k">def</span> <span class="nf">parse_details</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">response</span><span class="p">,</span> <span class="n">item</span><span class="p">):</span>
        <span class="c1"># populate more `item` fields</span>
        <span class="k">return</span> <span class="n">item</span>
</pre></div>
</div>
<p>基本上，这是一个简单的spider，它解析两页项目（start-url）。项目还有一个包含附加信息的详细信息页，因此我们使用 <code class="docutils literal notranslate"><span class="pre">cb_kwargs</span></code> 的功能 <a class="reference internal" href="request-response.html#scrapy.http.Request" title="scrapy.http.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a> 传递部分填充的项。</p><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
     style="display:block; text-align:center;"
     data-ad-layout="in-article"
     data-ad-format="fluid"
     data-ad-client="ca-pub-1466963416408457"
     data-ad-slot="8850786025"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
<div class="section" id="parse-command">
<h2>解析命令<a class="headerlink" href="#parse-command" title="永久链接至标题">¶</a></h2>
<p>检查蜘蛛输出的最基本方法是使用 <a class="reference internal" href="commands.html#std-command-parse"><code class="xref std std-command docutils literal notranslate"><span class="pre">parse</span></code></a> 命令。它允许在方法级别检查spider的不同部分的行为。它的优点是灵活和易于使用，但不允许在方法内部调试代码。</p>
<p>为了查看从特定URL中获取的项目：</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>$ scrapy parse --spider=myspider -c parse_item -d 2 &lt;item_url&gt;
[ ... scrapy log lines crawling example.com spider ... ]

&gt;&gt;&gt; STATUS DEPTH LEVEL 2 &lt;&lt;&lt;
# Scraped Items  ------------------------------------------------------------
[{&#39;url&#39;: &lt;item_url&gt;}]

# Requests  -----------------------------------------------------------------
[]
</pre></div>
</div>
<p>使用 <code class="docutils literal notranslate"><span class="pre">--verbose</span></code> 或 <code class="docutils literal notranslate"><span class="pre">-v</span></code> 选项我们可以看到每个深度级别的状态：</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>$ scrapy parse --spider=myspider -c parse_item -d 2 -v &lt;item_url&gt;
[ ... scrapy log lines crawling example.com spider ... ]

&gt;&gt;&gt; DEPTH LEVEL: 1 &lt;&lt;&lt;
# Scraped Items  ------------------------------------------------------------
[]

# Requests  -----------------------------------------------------------------
[&lt;GET item_details_url&gt;]


&gt;&gt;&gt; DEPTH LEVEL: 2 &lt;&lt;&lt;
# Scraped Items  ------------------------------------------------------------
[{&#39;url&#39;: &lt;item_url&gt;}]

# Requests  -----------------------------------------------------------------
[]
</pre></div>
</div>
<p>检查从一个开始的项目，也可以很容易地实现使用：：</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>$ scrapy parse --spider=myspider -d 3 &#39;http://example.com/page1&#39;
</pre></div>
</div>
</div>
<div class="section" id="scrapy-shell">
<h2>Scrapy Shell<a class="headerlink" href="#scrapy-shell" title="永久链接至标题">¶</a></h2>
<p>而 <a class="reference internal" href="commands.html#std-command-parse"><code class="xref std std-command docutils literal notranslate"><span class="pre">parse</span></code></a> 命令对于检查蜘蛛的行为非常有用，除了显示接收到的响应和输出之外，检查回调中发生的情况几乎没有帮助。如何调试情况 <code class="docutils literal notranslate"><span class="pre">parse_details</span></code> 有时没有收到物品？</p>
<p>幸运的是， <a class="reference internal" href="commands.html#std-command-shell"><code class="xref std std-command docutils literal notranslate"><span class="pre">shell</span></code></a> 在这种情况下，你的面包和黄油（见 <a class="reference internal" href="shell.html#topics-shell-inspect-response"><span class="std std-ref">从spiders调用shell来检查响应</span></a> ）：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">scrapy.shell</span> <span class="kn">import</span> <span class="n">inspect_response</span>

<span class="k">def</span> <span class="nf">parse_details</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">response</span><span class="p">,</span> <span class="n">item</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">item</span><span class="p">:</span>
        <span class="c1"># populate more `item` fields</span>
        <span class="k">return</span> <span class="n">item</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">inspect_response</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span>
</pre></div>
</div>
<p>参见： <a class="reference internal" href="shell.html#topics-shell-inspect-response"><span class="std std-ref">从spiders调用shell来检查响应</span></a> .</p>
</div>
<div class="section" id="open-in-browser">
<h2>在浏览器中打开<a class="headerlink" href="#open-in-browser" title="永久链接至标题">¶</a></h2>
<p>有时，您只想查看某个响应在浏览器中的外观，可以使用 <code class="docutils literal notranslate"><span class="pre">open_in_browser</span></code> 功能。以下是您将如何使用它的示例：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">scrapy.utils.response</span> <span class="kn">import</span> <span class="n">open_in_browser</span>

<span class="k">def</span> <span class="nf">parse_details</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">response</span><span class="p">):</span>
    <span class="k">if</span> <span class="s2">&quot;item name&quot;</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">response</span><span class="o">.</span><span class="n">body</span><span class="p">:</span>
        <span class="n">open_in_browser</span><span class="p">(</span><span class="n">response</span><span class="p">)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">open_in_browser</span></code> 将打开一个浏览器，此时Scrapy接收到响应，调整 <a class="reference external" href="https://www.w3schools.com/tags/tag_base.asp">base tag</a> 以便正确显示图像和样式。</p>
</div>
<div class="section" id="logging">
<h2>登录<a class="headerlink" href="#logging" title="永久链接至标题">¶</a></h2>
<p>日志记录是获取蜘蛛运行信息的另一个有用选项。尽管不太方便，但它的优点是，如果需要，日志在将来的所有运行中都将可用：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">parse_details</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">response</span><span class="p">,</span> <span class="n">item</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">item</span><span class="p">:</span>
        <span class="c1"># populate more `item` fields</span>
        <span class="k">return</span> <span class="n">item</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;No item received for </span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">response</span><span class="o">.</span><span class="n">url</span><span class="p">)</span>
</pre></div>
</div>
<p>有关详细信息，请检查 <a class="reference internal" href="logging.html#topics-logging"><span class="std std-ref">登录</span></a> 部分。</p>
</div>
</div>


           </div>
           
          </div>
          <footer>
  
    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
        <a href="contracts.html" class="btn btn-neutral float-right" title="蜘蛛合约" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a>
      
      
        <a href="../faq.html" class="btn btn-neutral float-left" title="常见问题" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a>
      
    </div>
  

  <hr/>

  <div role="contentinfo">
    <p>
        
        &copy; 版权所有 2008–2020, Scrapy developers
      <span class="lastupdated">
        最后更新于 10月 18, 2020.
      </span>

    </p>
  </div>
    
    
    
    Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a
    
    <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a>
    
    provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>

        </div>
      </div>

    </section>

  </div>
  

  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script>

  
  
    
  
 
<script type="text/javascript">
!function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){var e=document.createElement("script");e.type="text/javascript";e.async=!0;e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)};analytics.SNIPPET_VERSION="3.1.0";
analytics.load("8UDQfnf3cyFSTsM4YANnW5sXmgZVILbA");
analytics.page();
}}();

analytics.ready(function () {
    ga('require', 'linker');
    ga('linker:autoLink', ['scrapinghub.com', 'crawlera.com']);
});
</script>


</body>
</html>